﻿using System.Linq;
using Contracts.Entities;

namespace Model.MovieElements
{
    public class WriteCountries : WriteMovieElement
    {
        public WriteCountries(MovieDatabaseEntities entities, Movies movie)
            : base(entities, movie)
        {
        }

        public override void Insert(MovieElement element)
        {
            var entity = entities.Countries.SingleOrDefault(m => m.Name == element.Name);
            if (entity == null)
            {
                entity = CountryConverter.GetEntity(element);
                entity.Id = GetLastID() + 1;
            }

            movie.Countries.Add(entity);
            entities.SaveChanges();
        }

        public override void Delete(MovieElement element)
        {
            var country = movie.Countries.SingleOrDefault(m => m.Id == element.Id);

            if (country == null)
                return;

            movie.Countries.Attach(country);
            movie.Countries.Remove(country);
            entities.SaveChanges();
        }

        private int GetLastID()
        {
            var country = entities.Countries.OrderByDescending(m => m.Id).FirstOrDefault();
            return country != null ? country.Id : 0;
        }

        public override MovieElementType GetMovieElementType()
        {
            return MovieElementType.Country;
        }
    }
}
